import cv2
import numpy as np

# 读取图像
img = cv2.imread("12.jpg", )  # 0表示读取为灰度图像
imgRef = cv2.imread("an.png", )  # 匹配模板图像

# 计算原始图像直方图
histImg, bins = np.histogram(img.flatten(), 256, [0, 256])

# 计算匹配模板直方图
histRef, bins2 = np.histogram(imgRef.flatten(), 256, [0, 256])

# 计算累积分布函数 CDF
cdfImg = histImg.cumsum()
cdfRef = histRef.cumsum()

# 创建变换映射表
transM = np.zeros(256, dtype=int)

# 计算匹配后的图像
# 遍历每个可能的像素值（0到255），找到参考图像中与当前像素值的CDF最接近的值，并记录对应的像素值。
imgOut = img.copy()

for i in range(256):
    index = 0
    vMin = np.fabs(cdfImg[i] - cdfRef[0])
    for j in range(256):
        diff = np.fabs(cdfImg[i] - cdfRef[j])
        if (diff < vMin):
            index = int(j)
            vMin = diff
    transM[i] = index

# 应用变换映射表
imgOut = transM[img].astype(np.uint8)

# 显示结果
cv2.imshow("Original Image", img)
cv2.imshow("Reference Image", imgRef)
cv2.imshow("Transformed Image", imgOut)
cv2.waitKey(0)
cv2.destroyAllWindows()